<template>
  <div class="files-container">
    <el-card class="file-list">
      <template #header>
        <div class="card-header">
          <span>文件列表</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleUploadClick">
              上传文件
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        :data="files"
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="name" label="文件名" min-width="180" align="center" header-align="center">
          <template #default="{ row }">
            <div class="file-name">
              <el-icon :size="20">
                <component :is="getFileIcon(row.type)" />
              </el-icon>
              <span>{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="size" label="大小" min-width="100" align="center" header-align="center">
          <template #default="{ row }">
            {{ formatFileSize(row.size) }}
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" min-width="80" align="center" header-align="center" />
        <el-table-column prop="uploadTime" label="上传时间" min-width="160" align="center" header-align="center">
          <template #default="{ row }">
            {{ formatDate(row.uploadTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="200" fixed="right" align="center" header-align="center">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="primary" text @click="downloadFile(row)">
                下载
              </el-button>
              <el-button type="primary" text @click="shareFile(row)">
                分享
              </el-button>
              <el-button type="danger" text @click="deleteFile(row)">
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 上传文件对话框 -->
    <el-dialog
      v-model="showUploadDialog"
      title="上传文件"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="true"
      :show-close="true"
      destroy-on-close
    >
      <el-upload
        class="upload-demo"
        drag
        action="/api/file/upload"
        :headers="uploadHeaders"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :before-upload="beforeUpload"
        :data="uploadData"
        :auto-upload="true"
        :show-file-list="true"
        :limit="1"
        :multiple="false"
        accept="*/*"
        name="file"
        :http-request="customUpload"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            支持任意类型文件，单个文件大小不超过 100MB
          </div>
        </template>
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showUploadDialog = false">取消</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分享文件对话框 -->
    <el-dialog
      v-model="showShareDialog"
      title="分享文件"
      width="400px"
    >
      <el-form :model="shareForm" label-width="80px">
        <el-form-item label="有效期">
          <el-select v-model="shareForm.expiry" placeholder="请选择有效期">
            <el-option label="1天" value="1d" />
            <el-option label="7天" value="7d" />
            <el-option label="30天" value="30d" />
            <el-option label="永久" value="never" />
          </el-select>
        </el-form-item>
        <el-form-item label="访问密码">
          <el-input v-model="shareForm.password" placeholder="可选" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showShareDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmShare">
            确认分享
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { 
  ref, 
  onMounted,
  computed,
  watch
} from 'vue'
import { 
  ElMessage, 
  ElMessageBox,
  ElDialog,
  ElButton,
  ElUpload,
  ElTable,
  ElTableColumn,
  ElCard,
  ElIcon,
  ElForm,
  ElFormItem,
  ElSelect,
  ElOption,
  ElInput
} from 'element-plus'
import type { UploadProps } from 'element-plus'
import {
  Document,
  Picture,
  VideoPlay,
  Headset,
  UploadFilled
} from '@element-plus/icons-vue'
import 'element-plus/dist/index.css'

interface FileItem {
  id: number;
  originalFilename: string;
  size: number;
  userId: string;
  uploadTime: string;
  downloadUrl: string;
}

interface ApiResponse<T> {
  code: number;
  message: string;
  data: T;
  timestamp: number;
}

// 状态
const loading = ref(false)
const showUploadDialog = ref(false)
const showShareDialog = ref(false)
const files = ref<FileItem[]>([])
const currentFile = ref<FileItem | null>(null)
const shareForm = ref({
  expiry: '7d',
  password: ''
})

// 上传相关的数据
const uploadHeaders = computed(() => ({
  Authorization: `Bearer ${window.localStorage?.getItem('token') || ''}`,
  'Content-Type': 'application/json'
}))

const uploadData = computed(() => ({
  ownerId: window.localStorage?.getItem('user_uuid') || ''
}))

// 方法
const loadFiles = async () => {
  loading.value = true
  try {
    const response = await fetch('http://localhost:8081/api/file/list', {
      headers: {
        'Authorization': `Bearer ${window.localStorage?.getItem('token') || ''}`
      }
    });
    if (!response.ok) throw new Error('获取文件列表失败');
    const result: ApiResponse<FileItem[]> = await response.json();
    if (result.code === 200) {
      files.value = result.data.map((file: FileItem) => ({
        ...file,
        name: file.originalFilename, // 为了适配表格显示
        type: file.originalFilename.split('.').pop()?.toLowerCase() || '', // 从文件名获取类型
        uploadTime: new Date(file.uploadTime)
      }));
    } else {
      throw new Error(result.message || '获取文件列表失败');
    }
  } catch (error) {
    ElMessage.error('加载文件列表失败')
  } finally {
    loading.value = false
  }
}

const getFileIcon = (type: string) => {
  const iconMap = {
    doc: Document,
    docx: Document,
    pdf: Document,
    png: Picture,
    jpg: Picture,
    jpeg: Picture,
    mp4: VideoPlay,
    mp3: Headset
  }
  return iconMap[type] || Document
}

const formatFileSize = (size: number) => {
  if (size < 1024) {
    return size + 'B'
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(2) + 'KB'
  } else if (size < 1024 * 1024 * 1024) {
    return (size / (1024 * 1024)).toFixed(2) + 'MB'
  } else {
    return (size / (1024 * 1024 * 1024)).toFixed(2) + 'GB'
  }
}

const formatDate = (date: Date) => {
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const downloadFile = async (file: FileItem) => {
  try {
    const ownerId = window.localStorage?.getItem('user_uuid') || ''
    const response = await fetch(`http://localhost:8081/api/file/download/${file.id}?ownerId=${ownerId}`, {
      method: 'GET',
      headers: {
        Authorization: `Bearer ${window.localStorage?.getItem('token') || ''}`
      }
    })

    if (!response.ok) {
      throw new Error('下载文件失败')
    }

    // 获取文件名
    const contentDisposition = response.headers.get('content-disposition')
    let filename = file.originalFilename
    if (contentDisposition) {
      const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)
      if (filenameMatch && filenameMatch[1]) {
        filename = filenameMatch[1].replace(/['"]/g, '')
      }
    }

    // 创建 blob 并下载
    const blob = await response.blob()
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = filename
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)

    ElMessage.success('文件下载成功')
  } catch (error) {
    console.error('Download error:', error)
    ElMessage.error('下载文件失败：' + (error.message || '未知错误'))
  }
}

const shareFile = (file) => {
  currentFile.value = file
  showShareDialog.value = true
}

const confirmShare = async () => {
  try {
    // 这里应该调用后端 API 生成分享链接
    ElMessage.success('分享链接已生成')
    showShareDialog.value = false
  } catch (error) {
    ElMessage.error('生成分享链接失败')
  }
}

const deleteFile = async (file: FileItem) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个文件吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await fetch(`http://localhost:8081/api/file/delete/${file.id}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${window.localStorage?.getItem('token') || ''}`
      }
    })

    if (!response.ok) {
      const errorData = await response.json()
      throw new Error(errorData.message || '删除文件失败')
    }

    const result = await response.json()
    if (result.code === 200) {
      ElMessage.success('文件删除成功')
      // 重新加载文件列表
      await loadFiles()
    } else {
      throw new Error(result.message || '删除文件失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Delete error:', error)
      ElMessage.error('删除文件失败：' + (error instanceof Error ? error.message : '未知错误'))
    }
  }
}

const beforeUpload: UploadProps['beforeUpload'] = (file: File) => {
  const isLt100M = file.size / 1024 / 1024 < 100
  if (!isLt100M) {
    ElMessage.error('文件大小不能超过 100MB!')
    return false
  }
  return true
}

// 自定义上传方法
const customUpload = async (options: any) => {
  const { file, onSuccess, onError } = options
  const formData = new FormData()
  formData.append('file', file)
  formData.append('ownerId', uploadData.value.ownerId)

  try {
    const response = await fetch('http://localhost:8081/api/file/upload', {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${window.localStorage?.getItem('token') || ''}`
      },
      body: formData
    })

    if (!response.ok) {
      const errorData = await response.json()
      throw new Error(errorData.message || `Upload failed: ${response.statusText}`)
    }

    const result = await response.json()
    onSuccess(result)
  } catch (error) {
    console.error('Upload error:', error)
    onError(error)
  }
}

const handleUploadSuccess: UploadProps['onSuccess'] = (
  response: any,
  uploadFile: any
) => {
  if (response.code === 200) {
    ElMessage.success('文件上传成功')
    showUploadDialog.value = false
    loadFiles()
  } else {
    ElMessage.error(response.message || '文件上传失败')
  }
}

const handleUploadError: UploadProps['onError'] = (
  error: any,
  uploadFile: any
) => {
  console.error('Upload error:', error)
  ElMessage.error('文件上传失败：' + (error.message || '未知错误'))
}

// 添加处理上传按钮点击的方法
const handleUploadClick = () => {
  console.log('Upload button clicked')
  showUploadDialog.value = true
  console.log('showUploadDialog value:', showUploadDialog.value)
}

// 监听 showUploadDialog 的变化
watch(showUploadDialog, (newVal) => {
  console.log('showUploadDialog changed:', newVal)
})

// 确保在组件挂载时初始化状态
onMounted(() => {
  console.log('Component mounted')
  loadFiles()
  showUploadDialog.value = false
})
</script>

<style scoped lang="scss">
.files-container {
  position: relative;
  z-index: 1;
  padding: 20px;
  
  .file-list {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .file-name {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      
      .el-icon {
        color: #909399;
      }
    }
  }
}
</style> 